package cn.sell;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用lock解决数据安全问题
 * @author xzh
 */
public class SellTicketLock implements Runnable{
    private int ticket=100;
    private Lock lock=new ReentrantLock();
    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);//模拟出票时间
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                lock.lock();//加锁  只允许一个线程进来
                //this 方法是同步方法锁
                if (ticket >= 0) {
                    System.out.println(Thread.currentThread().getName() + ":正在卖第" + ticket + "张票");//正在卖第100张票
                    ticket--;//卖出一张票
                }
            }finally {//确保锁的释放
                lock.unlock();//释放锁
            }


        }
    }
}
